<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

// 查询参数
const operator = ref('ALL')
const networkType = ref('ALL')
const networkQuality = ref('下行速率')

const dateMinusDay = (date, days) => {
  const d = new Date(date)
  d.setDate(d.getDate() - days)
  return d
}
const lastWeek = dateMinusDay(new Date(), 7)
// 添加日期范围ref
const dateRange = ref({ start: lastWeek, end: new Date() })

// 下拉选项

const operatorOptions = ['ALL', 'CMCC', 'CTCC', 'CUCC']

const networkTypeOptions = ['ALL', '4G', '3G', '2G']

const networkQualityOptions = ['下行速率', '延迟', '上行速率']

// 提交查询
const submitQuery = () => {
  fetchChartData()
}

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const fetchChartData = async () => {
  try {
    const params = {
      dateRange: dateRange.value,
      operator: operator.value,
      networkType: networkType.value,
      networkQuality: networkQuality.value
    }
    const response2 = await axios.get('/api/network/rank', { })
    const { legends, seriesData, xaxisData } = response2.data.data

    if (!chart || !chartRef.value) return

    const option: echarts.EChartsOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params) {
          let result = params[0].name + '<br/>'
          params.forEach(param => {
            const unit = networkQuality.value === '延迟' ? 'ms' : 'Mbps'
            result += param.seriesName + ': ' + param.value + ' ' + unit + '<br/>'
          })
          return result
        }
      },
      legend: {
        data: legends,
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: xaxisData,
          axisLabel: {
            interval: 0,
            rotate: 0
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: networkQuality.value === '延迟' ?
                '网络延迟(ms)' :
                `网络${networkQuality.value}(Mbps)`
        }
      ],
      series: legends.map((legend, index) => ({
        name: legend,
        type: 'bar',
        data: seriesData[index],
        itemStyle: {
          color: legend === 'ALL' ? '#8BC34A' :     // 柔和的绿色
                 legend === 'CMCC' ? '#FF9B9B' :     // 淡珊瑚红
                 legend === 'CUCC' ? '#7FB8E6' :     // 淡蓝色
                 '#B39DDB'                           // 淡紫色
        },
        label: {
          show: false  // 只在鼠标悬停时显示数值
        },
        barMaxWidth: 50  // 控制柱子最大宽度
      }))
    }

    chart.setOption(option)
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

const initChart = () => {
  if (!chartRef.value) return
  chart = echarts.init(chartRef.value)
  fetchChartData()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => {
    chart?.resize()
  })
})

// 当任何查询参数变化时重新获取数据
watch([dateRange,  operator, networkType], () => {
  fetchChartData()
})
</script>

<template>
  <VaCard>
    <VaCardContent>
      <div class="flex flex-col justify-between gap-2 mb-4 md:flex-row">
        <div class="flex flex-col justify-start gap-2 md:flex-row">
          <VaDateInput v-model="dateRange" mode="range" label="日期范围" placeholder="日期范围" />
          <VaSelect v-model="operator" :options="operatorOptions" label="运营商" placeholder="运营商" />
          <VaSelect v-model="networkType" :options="networkTypeOptions" label="网络类型" placeholder="网络类型" />
           <VaSelect v-model="networkQuality" :options="networkQualityOptions" label="网络质量" placeholder="网络质量" />
        </div>
        <div class="flex gap-2">
          <VaButton @click="submitQuery">查询</VaButton>
        </div>
      </div>
      <!-- ECharts 容器 -->
      <div ref="chartRef" style="width: 100%; height: calc(100vh - 245px)"></div>
    </VaCardContent>
  </VaCard>
</template>

<style>
.va-date-input {
  width: 200px;
}
.va-select {
  width: 180px;
}
.va-button {
  margin-top: 16px;
  height: 35px;
  width: 80px;
}
</style>
